import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "../../components" as Components
import "../../styles" as Styles

Rectangle {
    id: taskDataGrid

    // 自定义属性
    property var taskListModel: null
    property string selectedChainId: ""

    // 信号
    signal taskSelected(string chainId)
    signal taskDeleted(string chainId)

    color: "transparent"

    ColumnLayout {
        anchors.fill: parent
        spacing: 0

        // 现代化表格头部
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 48
            color: Styles.Theme.backgroundSecondary
            radius: 8

            border.color: Styles.Theme.border
            border.width: 1

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: 16
                anchors.rightMargin: 16
                spacing: 12

                HeaderText { text: qsTr("任务名称"); Layout.preferredWidth: 80 }
                HeaderText { text: qsTr("状态"); Layout.preferredWidth: 100 }
                HeaderText { text: qsTr("进度"); Layout.fillWidth: true }
                HeaderText { text: qsTr("AGV"); Layout.preferredWidth: 100 }
                HeaderText { text: qsTr("创建时间"); Layout.preferredWidth: 140 }
                HeaderText { text: qsTr("操作"); Layout.preferredWidth: 80 }
            }
        }

        // 任务列表
        ListView {
            id: taskListView
            Layout.fillWidth: true
            Layout.fillHeight: true

            model: taskListModel
            clip: true
            spacing: 4

            // 性能优化
            cacheBuffer: 400
            reuseItems: true
            boundsBehavior: Flickable.StopAtBounds

            // 滚动条
            ScrollBar.vertical: ScrollBar {
                policy: ScrollBar.AsNeeded
                width: 8

                contentItem: Rectangle {
                    radius: 4
                    color: parent.pressed ? Styles.Theme.primary : Styles.Theme.border
                    opacity: parent.pressed ? 0.8 : 0.5

                    Behavior on color {
                        ColorAnimation { duration: 150 }
                    }
                }
            }

            delegate: Rectangle {
                id: taskItem

                required property string chainId
                required property string taskName
                required property int agvNumber
                required property string agvName
                required property string status
                required property string statusDisplay
                required property int currentTaskIndex
                required property int totalTasks
                required property int progress
                required property string createTime
                required property string errorMessage
                required property int index

                width: taskListView.width - 8
                height: errorMessage ? 84 : 64
                radius: 8

                color: {
                    if (selectedChainId === chainId) {
                        return Styles.Theme.backgroundSelected
                    }
                    if (taskItem.status === "timeout") {
                        return Qt.rgba(
                            Styles.Theme.warning.r,
                            Styles.Theme.warning.g,
                            Styles.Theme.warning.b,
                            0.2
                        )
                    }
                    return index % 2 === 0 ? Styles.Theme.background : Styles.Theme.backgroundAlternate
                }

                border.width: selectedChainId === chainId ? 2 : 1
                border.color: selectedChainId === chainId
                               ? Styles.Theme.primary
                               : (taskItem.status === "timeout"
                                    ? Styles.Theme.warning
                                    : Styles.Theme.border)

                Behavior on color {
                    ColorAnimation { duration: 150 }
                }

                Behavior on border.color {
                    ColorAnimation { duration: 150 }
                }

                // 鼠标悬停效果
                HoverHandler {
                    id: hoverHandler
                }

                // 点击选中
                TapHandler {
                    onTapped: {
                        selectedChainId = taskItem.chainId
                        taskSelected(taskItem.chainId)
                    }
                }

                // 内容布局
                ColumnLayout {
                    anchors.fill: parent
                    spacing: 0

                    RowLayout {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 64
                        Layout.leftMargin: 16
                        Layout.rightMargin: 16
                        spacing: 12

                        // 任务名称 - 带状态指示器
                        RowLayout {
                            Layout.preferredWidth: 80
                            spacing: 8

                            Rectangle {
                                width: 6
                                height: 6
                                radius: 3
                                color: getStatusColor(taskItem.status)

                                SequentialAnimation on opacity {
                                    running: taskItem.status === "executing"
                                    loops: Animation.Infinite
                                    NumberAnimation { from: 1.0; to: 0.3; duration: 800 }
                                    NumberAnimation { from: 0.3; to: 1.0; duration: 800 }
                                }
                            }

                            Text {
                                Layout.fillWidth: true
                                text: taskItem.taskName || "-"
                                color: Styles.Theme.textPrimary
                                font.pixelSize: 13
                                font.weight: Font.Medium
                                elide: Text.ElideRight
                            }
                        }

                        // 状态标签
                        Rectangle {
                            Layout.preferredWidth: 100
                            Layout.preferredHeight: 28
                            radius: 14
                            color: Qt.rgba(
                                getStatusColor(taskItem.status).r,
                                getStatusColor(taskItem.status).g,
                                getStatusColor(taskItem.status).b,
                                0.15
                            )

                            Text {
                                anchors.centerIn: parent
                                text: taskItem.statusDisplay
                                color: getStatusColor(taskItem.status)
                                font.pixelSize: 12
                                font.weight: Font.DemiBold
                            }
                        }

                        // 进度条
                        ColumnLayout {
                            Layout.fillWidth: true
                            spacing: 2

                            RowLayout {
                                spacing: 4

                                Text {
                                    text: taskItem.currentTaskIndex + "/" + taskItem.totalTasks
                                    color: Styles.Theme.textSecondary
                                    font.pixelSize: 11
                                }

                                Text {
                                    text: taskItem.progress + "%"
                                    color: Styles.Theme.primary
                                    font.pixelSize: 11
                                    font.weight: Font.Medium
                                }
                            }

                            Rectangle {
                                Layout.fillWidth: true
                                height: 4
                                radius: 2
                                color: Styles.Theme.border

                                Rectangle {
                                    width: parent.width * (taskItem.progress / 100)
                                    height: parent.height
                                    radius: parent.radius
                                    color: Styles.Theme.primary

                                    Behavior on width {
                                        NumberAnimation { duration: 300; easing.type: Easing.OutCubic }
                                    }
                                }
                            }
                        }

                        // AGV信息
                        RowLayout {
                            Layout.preferredWidth: 100
                            spacing: 6

                            Rectangle {
                                width: 24
                                height: 24
                                radius: 12
                                color: taskItem.agvNumber >= 0 ? Styles.Theme.primary : Styles.Theme.border
                                opacity: 0.2
                            }

                            Text {
                                text: taskItem.agvNumber >= 0 ? ("AGV" + taskItem.agvNumber) : "-"
                                color: taskItem.agvNumber >= 0 ? Styles.Theme.textPrimary : Styles.Theme.textSecondary
                                font.pixelSize: 13
                                font.weight: taskItem.agvNumber >= 0 ? Font.Medium : Font.Normal
                            }
                        }

                        // 创建时间
                        Text {
                            Layout.preferredWidth: 140
                            text: taskItem.createTime
                            color: Styles.Theme.textSecondary
                            font.pixelSize: 12
                            elide: Text.ElideRight
                        }

                        // 删除按钮
                        Item {
                            Layout.preferredWidth: 80
                            Layout.fillHeight: true

                            Components.ActionButton {
                                anchors.centerIn: parent
                                size: "small"
                                text: qsTr("删除")
                                iconSource: ""
                                buttonType: "danger"
                                opacity: hoverHandler.hovered ? 1.0 : 0.6

                                onClicked: {
                                    taskDeleted(taskItem.chainId)
                                }

                                Behavior on opacity {
                                    NumberAnimation { duration: 150 }
                                }
                            }
                        }
                    }

                    // 错误提示（如果有）
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 24
                        Layout.leftMargin: 16
                        Layout.rightMargin: 16
                        Layout.bottomMargin: 4
                        visible: taskItem.errorMessage
                        color: "#FFF3CD"
                        radius: 4

                        RowLayout {
                            anchors.fill: parent
                            anchors.leftMargin: 8
                            anchors.rightMargin: 8
                            spacing: 6

                            Text {
                                text: "⚠"
                                color: "#856404"
                                font.pixelSize: 14
                            }

                            Text {
                                Layout.fillWidth: true
                                text: taskItem.errorMessage
                                color: "#856404"
                                font.pixelSize: 11
                                elide: Text.ElideRight
                            }
                        }
                    }
                }
            }

            // 空状态提示
            Label {
                anchors.centerIn: parent
                visible: taskListView.count === 0
                text: qsTr("暂无任务")
                color: Styles.Theme.textSecondary
                font.pixelSize: 16
            }
        }
    }

    // 辅助组件：表头文本
    component HeaderText: Text {
        color: Styles.Theme.textSecondary
        font.pixelSize: 12
        font.weight: Font.DemiBold
        verticalAlignment: Text.AlignVCenter
    }

    // 辅助函数：获取状态颜色
    function getStatusColor(status) {
        switch (status) {
            case "executing":
            case "running":
                return Styles.Theme.primary
            case "completed":
            case "finished":
                return Styles.Theme.success
            case "failed":
            case "error":
                return Styles.Theme.danger
            case "timeout":
                return Styles.Theme.warning
            case "cancelled":
                return Styles.Theme.textSecondary
            case "pending":
            default:
                return Styles.Theme.warning
        }
    }
}
